package it.free.maya.worddistinct;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

/**
 * Extract a sorted list from a list, sorting by number of ocurences
 * @author Stefano Falconetti
 */
public class WordsSorting {

	private HashMap<String, Word> values = null;
	
	private Logger logger = Logger.getLogger(WordsSorting.class);
	
	/**
	 * Class builder
	 * @param listOfWords is the list of words to sort
	 */
	public WordsSorting(HashMap<String, Word> listOfWords){
		this.values = listOfWords;
	}
	
	/**
	 * Sort the list by number of occurrences for first
	 * @param values the list of words
	 * @return a sorted list of words ordered by highest number of occurrences for first
	 */
	private List<Word> getSortedList() throws Exception {
		
		logger.info("Sorting " + values.size() + " values by word occurences number");
		
		List<Word> sortedListOfWords = new ArrayList<Word>();
		
		Set<String> distinctWordsKeys = values.keySet();
		String tmpKey = null;
		Word tmpWord = null;
		int lastOccurencesValue = 0;
		Iterator<String> distinctWordsKeysIterator = null;
		
		String sortedListKey = null;
		
		int itemsToProcess = values.size();
		
		for(int i=0; i < itemsToProcess; i++){
			
			distinctWordsKeysIterator = distinctWordsKeys.iterator();
		
			while(distinctWordsKeysIterator.hasNext()){
				  tmpKey = distinctWordsKeysIterator.next();
			      tmpWord = values.get(tmpKey);
			      
			      if(tmpWord.getOccurencesCounter() > lastOccurencesValue){
			    	 sortedListKey = tmpWord.getWord();
			    	 lastOccurencesValue = tmpWord.getOccurencesCounter();
			      }
			}
			sortedListOfWords.add(values.get(sortedListKey));
			distinctWordsKeys.remove(sortedListKey);
			lastOccurencesValue = 0;
		}
		
		logger.info("Sort done");
		
		return sortedListOfWords;
	}
	
	public List<Word> process() throws Exception {
		return this.getSortedList();
	}
}
